package com.liaofan.rocketmq.producer;


import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.concurrent.TimeUnit;

/**
 * 异步发送消息的类
 */
public class NotSyncProducer {
    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        DefaultMQProducer producer = new DefaultMQProducer("pg");
        producer.setNamesrvAddr("192.168.153.129:9876");
        //指定新创建的Topic的Queue数量为2，默认为4
        producer.setDefaultTopicQueueNums(2);
        producer.start();

        for (int i = 0; i < 100; i++) {
            byte[] body = ("Hi,Liaofan" + i).getBytes();
            Message msg = new Message("someTopic_NotSync_A", "someTag_T1", body);
            msg.setKeys("Just Do it_NotSync:" + i);

            //异步发送消息，指定回调
            producer.send(msg, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println(sendResult);
                }

                @Override
                public void onException(Throwable throwable) {

                }
            });

        }
        TimeUnit.SECONDS.sleep(3);
        producer.shutdown();
    }
}
